package com.myapp.handler;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;

import org.apache.log4j.Logger;

import com.myapp.msg.base.BaseMsg;

/**
 * 编码器
 * 
 * @author jay 2011-4-20
 */
public class Encoder {
	// 日志
	private static Logger logger = Logger.getLogger(Encoder.class);

	public static ByteBuffer encode(List<? extends BaseMsg> msgs) {
		try {
			// 准备输出数据
			ByteBuffer byteBuffer = ByteBuffer.allocate(512);

			// 留出二个字节长度的做数据长度
			byteBuffer.position(4);
			for (BaseMsg baseMsg : msgs) {
				byteBuffer = baseMsg.writeBase(byteBuffer);
			}
			byteBuffer.flip();

			// 增加数据长度
			int length = byteBuffer.limit();
			if (length > Integer.MAX_VALUE) {
				throw new IOException(String.format(
						"Msg is too long[length:%d]!", length));
			}
			byteBuffer.putInt(length - 4);
			byteBuffer.position(0);
			byteBuffer.limit(length);

			return byteBuffer;
		} catch (Exception e) {
			logger.error("Encode Message Error!", e);
		}
		return null;
	}
}
